<template>
  <div>
    <basic-container>
      <avue-data-display :option="totalOption"></avue-data-display>
      <el-tabs v-model="tabtype" @tab-click="tabChange">
        <el-tab-pane label="我的订单" name="first">
          <avue-crud
            :data="orderOption.tableData"
            :page="orderOption.page"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :option="orderOption"
            @refresh-change="getOrderList"
          >
            <template slot-scope="scope" slot="orderNo">
              <span
                style="color:blue; cursor:pointer;"
                @click="handleDetail(scope.row)"
              >{{scope.row.orderNo}}</span>
            </template>

            <template slot="menuLeft">
              <div class="el-form el-form--inline">
                <div class="el-form-item">
                  <el-date-picker
                    v-model="searchBoard.orderDt"
                    type="daterange"
                    @change="getOrderList(true)"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </div>
              </div>
            </template>

            <!-- <template slot="menu">
                <el-button type="primary" @click="handleDetail(scope.row)" size="small">查看</el-button>              
            </template> -->

            <template slot-scope="scope" slot="orderFlag">
              <span>{{mapFlag(scope.row.orderFlag)}}</span>
            </template>
          </avue-crud>
        </el-tab-pane>
        <el-tab-pane label="提现记录" name="second">
          <avue-crud
            :data="withdrawOption.tableData"
            :option="withdrawOption"
            @refresh-change="getWithdrawList"
            :page="withdrawOption.page"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
            <template slot="menuLeft">
              <div class="el-form el-form--inline">
                <div class="el-form-item">
                  <el-date-picker
                    v-model="searchBoard.withdrawDt"
                    type="daterange"
                    @change="getWithdrawList(true)"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </div>

                <div class="el-form-item">
                  <el-button type="primary" @click="openWithdrawDialog()" size="small">提现</el-button>
                </div>

                <div class="el-form-item">
                  <el-button type="primary" @click="openBankDialog()" size="small">绑定银行卡</el-button>
                </div>
              </div>
            </template>
          </avue-crud>
        </el-tab-pane>
      </el-tabs>

      <el-dialog
        title="银行卡信息"
        :visible.sync="bank.show"
        width="30%"
        :before-close="closeBankDialog"
      >
        <el-form label-width="80px;" ref="bankForm" :model="bank.info" :rules="bank.rules">
          <el-form-item label="卡号" prop="card_number">
            <el-input v-model="bank.info.card_number" placeholder required></el-input>
          </el-form-item>
          <el-form-item label="开户行" prop="bank_name">
            <el-input v-model="bank.info.bank_name" placeholder required></el-input>
          </el-form-item>
          <el-form-item label="户主" prop="name">
            <el-input v-model="bank.info.name" placeholder required></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="bank.info.phone" placeholder required></el-input>
          </el-form-item>
          <el-form-item label="密码验证" prop="password">
            <el-input type="password" v-model="bank.info.password" placeholder required></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeBankDialog">取 消</el-button>
          <el-button type="primary" @click="updateBankInfo">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="提现申请"
        :visible.sync="withdraw.show"
        width="30%"
        :before-close="closeWithdrawDialog"
      >
        <div>
          <span>到账银行卡</span>
          {{bankCard}}
        </div>
        <div>提现金额</div>
        <el-input v-model="withdraw.withdrawMoney" placeholder="输入提现金额"></el-input>
        <div>
          提现金额最低100起
          余额：{{withdraw.info.money}}元，
          <br>
          手续费: {{cashFee}} (费率: {{withdraw.info.cash_fee}}%, 从提现金额中扣除)
          <!-- 可得金额:{{}} -->
          <!-- <span
            @click="withdrawAll"
          >全部提现</span>-->
        </div>密码：
        <el-input type="password" v-model="withdraw.password" placeholder required></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeWithdrawDialog">取 消</el-button>
          <el-button type="primary" @click="sendWithdraw">提 现</el-button>
        </span>
      </el-dialog>

      <detail ref="detail" method="showOrder"></detail>
    </basic-container>
  </div>
</template>

<script>
/* eslint-disable */
import { mapGetters } from "vuex";
import crudMixin from '@/mixins/crud'
import options from "./options.js";
import { isNull, arr2pojo, obj2pojo, validateResponse } from "@/util/util";
import { successMsg, errorMsg } from "@/util/message"
import { field, reField } from "./field";
import { BigNumber } from 'bignumber.js';
import detail from "@/views/merchant/common/detail";


export default {
  name: "role",
  mixins: [crudMixin],
  components: {
    detail
  },
  data() {
    return Object.assign({}, options, {
      bank: {
        show: false,
        info: {
          id: '',
          card_number: '',
          bank_name: '',
          name: '',
          phone: '',
          password: ''
        },
        rules: {
          card_number: [
            { required: true, message: '请输入银行卡号', trigger: 'blur' },
          ],
          bank_name: [
            { required: true, message: '请输入银行名称', trigger: 'blur' },
          ],
          name: [
            { required: true, message: '请输入联系人', trigger: 'blur' },
          ],
          phone: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
          ],
          password: [
            { required: true, message: '请输入登陆用户密码', trigger: 'blur' },
          ],
        }
      },
      withdraw: {
        show: false,
        info: {
          money: '',
          cash_fee: '',
        },
        withdrawMoney: 100,
        password: ''
      }
    })
  },
  created() {
    //初始化数据格式
    this.getOrderList();
  },
  watch: {},
  mounted() { },
  computed: {
    bankCard() {
      // 隐藏并拼接
      let no = this.bank.info.card_number.slice(-4)
      return this.bank.info.bank_name + '(' + no + ')'
    },
    cashFee() {
      return ((this.withdraw.withdrawMoney * this.withdraw.info.cash_fee) / 100).toFixed(2)
    },
    canGetMoney() {
      let withdrawMoney = new BigNumber(this.withdraw.withdrawMoney)
      return withdrawMoney.minus(this.cashFee)
    },
    // 判断是否可以提现
    canWithdraw() {
      let withdrawMoney = new BigNumber(this.withdraw.withdrawMoney)

      if (withdrawMoney.minus(this.cashFee).isLessThanOrEqualTo(this.withdraw.info.money))      {
        return true
      }
      return false
    },
    checkWithdraw() {
      if (isNull(this.withdraw.withdrawMoney)) return false
      let withdrawMoney = new BigNumber(this.withdraw.withdrawMoney)
      if (withdrawMoney.isLessThan(100)) return false
      return true
    }
  },
  props: [],
  methods: {
    mapFlag(value) {
      var result = ''
      let flag = ['待付款', '订单取消', '等待发货', '等待发货', '订单取消', '待用户确认取消', '订单取消', '已发货', '已完成', '用户取消待确认']

      return flag[value]
    },
    getOrderList(init = false) {
      if (init)
      {
        this.orderOption.page.currentPage = 1
      }
      this.tableLoading = true;
      let param = Object.assign({}, {
        perPage: this.orderOption.page.pageSize,
        page: this.orderOption.page.currentPage,
        orderDt: this.searchBoard.orderDt,
      });
      this.orderOption.tableData = [];
      this.orderOption.page.total = 0;

      this.$store.dispatch("GetFundInfo", param)
        .then(res => {
          this.tableLoading = false;
          if (res.data.status == 1 && res.data.result.data.totalInfo != null)          {
            this.totalOption.data[0].count = res.data.result.data.totalInfo.incomeamount;
            this.totalOption.data[1].count = res.data.result.data.totalInfo.assetamount;
            this.totalOption.data[2].count = res.data.result.data.totalInfo.leftamount;
            this.totalOption.data[3].count = res.data.result.data.totalInfo.freezeamount;

            this.orderOption.tableData = res.data.result.data.orderList.data;
            this.orderOption.page.total = res.data.result.data.orderList.meta.total;
            
          }
        }, error => {
          this.tableLoading = false;
        })
    },
    //查询提现记录
    getWithdrawList(init = false) {
      if (init)
      {
        this.withdrawOption.page.currentPage = 1
      }
      this.tableLoading = true;
      let param = Object.assign({}, {
        perPage: this.withdrawOption.page.pageSize,
        page: this.withdrawOption.page.currentPage,
        withdrawDt: this.searchBoard.withdrawDt,
      });
      this.withdrawOption.tableData = [];
      this.withdrawOption.page.total = 0;

      this.$store.dispatch("GetWithdrawRecord", param)
        .then(res => {
          this.tableLoading = false;
          if (res.data.status == 1 && res.data.result.data.totalInfo != null)          {
            this.totalOption.data[0].count = res.data.result.data.totalInfo.incomeamount;
            this.totalOption.data[1].count = res.data.result.data.totalInfo.assetamount;
            this.totalOption.data[2].count = res.data.result.data.totalInfo.leftamount;
            this.totalOption.data[3].count = res.data.result.data.totalInfo.freezeamount;


            this.withdrawOption.tableData = res.data.result.data.withdrawList.data;
            this.withdrawOption.page.total = res.data.result.data.withdrawList.meta.total;
          }
        }, error => {
          this.tableLoading = false;
        })
    },
    tabChange(tab, event) {
      if (this.tabtype == 'first')
      {
        this.getOrderList(true);
      }
      else if (this.tabtype == 'second')      {
        this.getWithdrawList(true);
      }
    },
    openBankDialog() {
      // 更新银行卡信息
      this.$store.dispatch('GetWithdrawInfo', {}).then(res => {
        if (res.data.status == 1)
        {
          let bank = res.data.result.data.bank
          if (!isNull(bank))
          {
            this.bank.info.card_number = bank.card_number
            this.bank.info.bank_name = bank.bank_name
            this.bank.info.name = bank.name
            this.bank.info.phone = bank.phone
          }
        }
        else        {
          errorMsg(this, '获取数据错误')
        }
      }), error => {
        errorMsg(this, '获取数据错误')
      }


      // let bank = this.$store.getters.userInfo.userData.bank


      this.bank.show = true
    },
    closeBankDialog() {
      this.bank.show = false
    },
    updateBankInfo() {
      this.$refs['bankForm'].validate((valid) => {
        if (valid)        {
          this.$confirm('是否确认更新提现银行卡信息?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('UpdateBankInfo', this.bank.info).then((res) => {
              console.log(res)
              if (res.data.status == 1)
              {
                // 更新成功
                successMsg(this, '更新成功')
                this.$store.getters.userInfo.userData.bank = {
                  card_number: this.bank.info.card_number,
                  bank_name: this.bank.info.bank_name,
                  name: this.bank.info.name,
                  phone: this.bank.info.phone,
                }
                this.bank.show = false
              }
              else              {
                errorMsg(this, res.data.message)
              }
            }, error => {
              errorMsg(this, '更新失败')
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '更新失败'
            });
          });
        } else        {
          return false;
        }
      });
    },
    openWithdrawDialog() {
      this.$store.dispatch('GetWithdrawInfo', {}).then((res) => {
        if (res.data.status == 1)
        {
          let data = res.data.result.data
          let bank = data.bank
          if (isNull(bank))
          {
            return errorMsg(this, '请先绑定银行卡')
          }
          else          {
            this.bank.info.id = bank.id
            this.bank.info.card_number = bank.card_number
            this.bank.info.bank_name = bank.bank_name
            this.bank.info.name = bank.name
            this.bank.info.phone = bank.phone
          }
          this.withdraw.info.money = data.money
          this.withdraw.info.cash_fee = data.cash_fee
          this.withdraw.show = true
        }
        else        {
          errorMsg(this, '获取数据错误')
        }
      })
    },
    closeWithdrawDialog() {
      this.withdraw.show = false
    },
    sendWithdraw() {
      if (isNull(this.withdraw.password))
      {
        return errorMsg(this, '密码不能为空')
      }
      if (!this.checkWithdraw)
      {
        return errorMsg(this, '提现金额不得小于100元')
      }
      if (this.canWithdraw)
      {
        this.$store.dispatch('StoreWithdraw', {
          money: this.withdraw.withdrawMoney,
          cash_fee: this.cashFee,
          bank_id: this.bank.info.id,
          password: this.withdraw.password
        }).then(res => {
          if (res.data.status == 1)          {
            successMsg(this, '提现成功')
            // 隐藏窗口
            this.withdraw.show = false
            this.getWithdrawList()
            // 刷新记录
          } else          {
            errorMsg(this, res.data.message)
          }
        }), error => {
          errorMsg(this, '提现失败')
        }
      }
      else      {
        errorMsg(this, '超过最大提现金额')
      }
    },
    withdrawAll() {
      //根据money计算金额
      let withdrawMoney = new BigNumber(this.withdraw.info.money)
      let cashFeePersen = new BigNumber(this.withdraw.info.cash_fee / 100 + 1)
      let maxWithdraw = withdrawMoney.dividedBy(cashFeePersen)
      this.withdraw.withdrawMoney = maxWithdraw.toFixed(2)
    },
    handleSizeChange(size) {
      if (this.tabtype == 'first')
      {
        this.orderOption.page.pageSize = size
        this.getOrderList()
      }
      else if (this.tabtype == 'second')      {
        this.withdrawOption.page.pageSize = size
        this.getWithdrawList();
      }

    },
    handleCurrentChange(page) {
      if (this.tabtype == 'first')
      {
        this.orderOption.page.currentPage = page
        this.getOrderList()
      }
      else if (this.tabtype == 'second')      {
        this.withdrawOption.page.currentPage = page
        this.getWithdrawList();
      }
    },
    handleDetail(row) {
      console.log(row.id)
      this.$nextTick(() => {
        this.$refs.detail.handleShow(row.id)
      })
    }
  }
};
</script>
